package com.sdsy.util;

import com.sdsy.constant.ResultErrorInfo;
import com.sdsy.entity.ResultEntity;
import com.sdsy.service.PageHelperService;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class PageFormatHelper extends LinkedHashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	//总页数
	private int totalPages;
	// 当前页数
	private int pageIndex;
	//每页条数
	private int pageSize;
	//总记录条数
	private int totalRows;
	
	/**计算分页参数
	 * @param params
	 * @param totalRows
	 */
	public PageFormatHelper(Map<String, Object> params, int totalRows) {
		this.putAll(params);
		this.totalRows = totalRows;
		
		// 分页参数
		this.pageIndex = Integer.parseInt(params.get("pageIndex").toString());
		this.pageSize = Integer.parseInt(params.get("pageSize").toString());
		
		this.put("startNum", String.valueOf((pageIndex-1)*pageSize));
		this.put("endNum", String.valueOf(pageIndex*pageSize));
		
		//计算总页数
		totalPages = totalRows / pageSize;
		int mod = totalRows % pageSize;
		if (mod > 0) {
			totalPages++;
		}
	}
	
	/**判断当前页码是否超出最后一页或小于第一页
	 * @param query
	 * @return
	 */
	public static ResultEntity validPageIndex(PageFormatHelper query){
		if(query.getPageIndex() <=0 ){
			return ResultEntity.fail(ResultErrorInfo.ONE_PAGE_INDEX);
		} else if(query.getPageIndex() > query.getTotalPages()){
			return ResultEntity.fail(ResultErrorInfo.LAST_PAGE_INDEX);
		} else {
			return ResultEntity.success();
		}
	}
	
	/**
	 * 获取分页数据
	 * @param service
	 * @param params
	 * @return
	 */
	public static PageResult pageHelper(Object service, Map<String, Object> params){
		PageHelperService ps = (PageHelperService) service;
		
		//获取总记录数
		int totalRows = ps.count(params);
		
		//生成分页参数
		PageFormatHelper query = new PageFormatHelper(params, totalRows);
		
		//获取分页数据
		List<?> pageList = ps.list(query);
		
		//生成分页返回对象
		PageResult pageResult = new PageResult(pageList, query);
		return pageResult;
	}
	

	public int getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalPages() {
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}
	
	public int getTotalRows() {
		return totalRows;
	}

	public void setTotalRows(int totalRows) {
		this.totalRows = totalRows;
	}
	
}

